//
//  WYJComposeViewController.swift
//  MySinaWeibo
//
//  Created by eastriver on 17/4/4.
//  Copyright © 2017年 believewilliam. All rights reserved.
//

import UIKit
import SVProgressHUD
class WYJComposeViewController: UIViewController {
    
    private lazy var sendBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.addTarget(self, action: #selector(rightBtnDidClick), for: .touchUpInside)
        return btn
        
    }()
    
    private lazy var composeTextView: UITextView = {
        let tv = UITextView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight / 3))
        tv.backgroundColor = randomColor()
        tv.font = UIFont.systemFont(ofSize: 16)
        // 滚动令键盘消失
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()
    
    lazy var placeholderLabel: UILabel = UILabel(title: "青山遮不住，毕竟东流去", textColor: UIColor.lightGray, fontSize: 16)
    
    private lazy var composeToolBar: UIToolbar = {
       let toolBar = UIToolbar()
        var barBtnItemArray = [UIBarButtonItem]()
        let imageNames = ["compose_toolbar_picture",
                    "compose_mentionbutton_background",
                        "compose_trendbutton_background",
                    "compose_emoticonbutton_background",
                          "compose_add_background"]
        for value in imageNames.enumerated() {
            let btn = UIButton()
            btn.setImage(UIImage(named: value.element), for: .normal)
            btn.setImage(UIImage(named: value.element + "_highlighted"), for: .highlighted)
            btn.addTarget(self, action: #selector(statusTypeBtnDidClick(statusTypeBtn:)), for: .touchUpInside)
            btn.tag = value.offset
            btn.sizeToFit()
            let btnItem = UIBarButtonItem(customView: btn)
            barBtnItemArray.append(btnItem)
            // 添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            barBtnItemArray.append(space)
                    }
        barBtnItemArray.removeLast()
        toolBar.items = barBtnItemArray
        return toolBar
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        setupNavBar()
        setupTextView()
        setupToolBar()
        // 向通知中心注册一个观察者
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
    }
    
    private func setupNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: "", target: self, action: #selector(leftBtnDidClick))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        self.navigationItem.rightBarButtonItem?.isEnabled = false
        // 设置titleView
        if let userName = WYJUserAccountViewModel.sharedAccountViewModel.userAccount?.name {
            
            let titleLabel = UILabel()
            // 使用富文本设置
            let titleText = "发布微博\n\(userName)"
            let mutableAttr = NSMutableAttributedString(string: titleText)
            
            let subRange = (titleText as NSString).range(of: userName)
            mutableAttr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13), NSForegroundColorAttributeName: UIColor.orange], range: subRange)
            titleLabel.attributedText = mutableAttr
            // 据UILabel的attributedText属性注释知，设置titleLabel的该属性后，titleLabel的textAlignment等其它属性就被忽略了，即设置了也没有意义。但是numberOfLines属性不在被忽略之列。
            //            titleLabel.textAlignment = .center
            titleLabel.numberOfLines = 0 // 我不明白上面titleText中已经有了换行符，为什么还要设置这个属性。但是不设置，效果确实不对。
            titleLabel.sizeToFit()
            self.navigationItem.titleView = titleLabel
        }
        
        
    }
    
    private func setupTextView() {
        self.view.addSubview(composeTextView)
        composeTextView.addSubview(placeholderLabel)
        placeholderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(composeTextView).offset(8)
            make.left.equalTo(composeTextView).offset(5)
        }
    }
    
    private func setupToolBar() {
        self.view.addSubview(composeToolBar)
        composeToolBar.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
        }
    }
    
    @objc private func leftBtnDidClick() {
        self.dismiss(animated: true, completion: nil)
    }
    @objc private func rightBtnDidClick() {
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let parameters = ["access_token": WYJUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token ?? "", "status": composeTextView.text ?? ""]
        WYJNetworkTool.sharedTool.request(method: .POST, urlString: urlString, parameters: parameters) { (_, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "发布微博失败,请重试")
            }
            SVProgressHUD.showSuccess(withStatus: "发布微博成功")
        }
    }
    @objc private func statusTypeBtnDidClick(statusTypeBtn: UIButton) {
        switch statusTypeBtn.tag {
        case 0:
            print(statusTypeBtn.tag)
        case 1:
            print(statusTypeBtn.tag)
        case 2:
            print(statusTypeBtn.tag)
        case 3:
            print(statusTypeBtn.tag)
        default:
            print(statusTypeBtn.tag)
        }
    }
    @objc private func keyboardWillChange(noti: NSNotification) {
//        print(noti)
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let offsetY = screenHeight - endFrame.origin.y
     // 更新composeToolBar的底部约束
        self.composeToolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(-offsetY)
        }
        // 不明白为何写了下面代码后，composeToolBar向上移动就有了动画效果。
        UIView.animate(withDuration: 0.25) {
            self.view.layoutIfNeeded()
        }
    }
    deinit {
        // 从通知中心中移除观察者
        NotificationCenter.default.removeObserver(self)
    }
}

extension WYJComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
       self.navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        placeholderLabel.isHidden = textView.hasText
    }
}
